<?php
/**
 *
 * 用户消息通知
 */
class User_Info_Notice
{
	const _CONST_TB_INFO_ = 'user_info';

	private $_user_id, $_cache_key;

	public function __construct ($uid)
	{
		$this->_user_id   = (int) $uid;
		$this->_cache_key = Kohana::config('user.notice.cache_prefix').$this->_user_id;
	}

	public function count () 
	{
		$n   = Cache::instance()->get($this->_cache_key);

		if ($n === NULL)
		{
			$n = $this->get();
			if (empty($n))
				$n = 0;

			Cache::instance()->set($this->_cache_key, $n, 600);
		}

		return (int) $n;
	}

	public function clean ()
	{
		$this->set(0);
		Cache::instance()->set($this->_cache_key, 0);
		return TRUE;
	}

	public function increase ()
	{
		$expr = DB::expr('`notice`+1');
		$this->set($expr);
		$n    = $this->get();

		Cache::instance()->set($this->_cache_key, $n);
		return $n;
	}

	private function set ($n)
	{
		$rows = DB::update(self::_CONST_TB_INFO_)
			->set(array('notice' => $n))
			->where('uid', '=', $this->_user_id)
			->execute();

		if ($rows == 0)
		{
			$rows = DB::select('uid')
				->from (self::_CONST_TB_INFO_)
				->where('uid', '=', $this->_user_id)
				->execute()
				->get('uid');

			if ($rows <= 0)
				DB::insert(self::_CONST_TB_INFO_)
					->columns(array('uid', 'notice'))
					->values(array($this->_user_id, $n))
					->execute();
		}
	}

	private function get ()
	{
		return DB::select('notice')
			->from(self::_CONST_TB_INFO_)
			->where('uid', '=', $this->_user_id)
			->execute()
			->get('notice');
	}

	private function get_statistics_count ()
	{
		$type   = 'status';
		$start_time = NULL;
		$end_time   = NULL;
		$result = Order::statistics($type, $start_time, $end_time, $this->_user_id);
		$r =& $result;
		if ($this->_user_id == user::current_merchant_uid())
			return $r['paid'] + $r['wait_merchant_confirm'] + $r['cmt_wait_reply'];
		else
			return $r['unpaid'] + $r['sent'] + $r['cmt_wait_reply'];
	}
}
